<template>
  <div class="mala-indicator">
    <div class="mala-indicator-content" ref="contentRef">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "mala-indicator"
}
</script>

<script setup>
import { watch, ref, onMounted } from "vue"
// props
const props = defineProps({
  selectIndex: {
    type: Number,
    require: true
  }
})
// 组件状态
const contentRef = ref(null)
// 组件副作用
onMounted(() => {
  // 监听props的变化
  watch(props, (newProps) => {
    // 容器
    const contentEl = contentRef.value
    // 选中元素
    const selectEl = contentEl.children[newProps.selectIndex]
    // 容器宽度
    const contentWidth = contentEl.clientWidth
    // 容器可滚动距离
    const contentScroll = contentEl.scrollWidth
    // 选中元素距离左端距离
    const itemLeft = selectEl.offsetLeft
    // 选中元素宽度
    const itemWidth = selectEl.clientWidth
    // 滚动距离
    let distance = itemLeft + itemWidth * 0.5 - contentWidth * 0.5
    // 左边特殊请况处理
    if (distance < 0) distance = 0
    // 右边特殊情况处理
    const totalDistance = contentScroll - contentWidth
    if (distance > totalDistance) distance = totalDistance
    // 滚动
    contentEl.style.transform = `translateX(${-distance}px)`
  }, { immediate: true })
})
</script>